package tgeo;

import java.util.UUID;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

public class NewViewHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		String secondaryId = UUID.randomUUID().toString();
		Command cmd = event.getCommand();
		String cmdName = "";
		try {
			cmdName = cmd.getName();
		} catch (NotDefinedException e1) {
			e1.printStackTrace();
		}
		if("Exit".equals(cmdName)){
			HandlerUtil.getActiveWorkbenchWindow(event).close();
			return null;
		}
		IWorkbenchPage page = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
		try {
			String viewID = "tgeo.views." + cmd.getName();
			IViewPart view = page.findView(viewID);
			if(view == null){
				view = page.showView(viewID);
			}else{
				page.bringToTop(view);
				view = page.showView(viewID, "" + secondaryId, IWorkbenchPage.VIEW_CREATE);
				page.bringToTop(view);
//				secondaryID++;
			}
		} catch (PartInitException e) {
			// not allowMultiple
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
